package cn.sh.library.mgts.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Enumeration;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import cn.sh.library.mgts.bean.CommonSearchBean;
import cn.sh.library.mgts.bean.InstanceSearchBean;
import cn.sh.library.mgts.bean.PlaceMapBean;
import cn.sh.library.mgts.bean.ResponseBean;
import cn.sh.library.mgts.dto.Pager;
import cn.sh.library.mgts.framework.commonparser.ParseException;
import cn.sh.library.mgts.service.IndexService;
import cn.sh.library.mgts.service.InstanceService;

@Controller
@RequestMapping("/mgts")
public class InstanceController {
	@Autowired
	IndexService indexService;

	@Resource
	private InstanceService mgtsInstanceService;

	private static Logger logger = LoggerFactory.getLogger(InstanceController.class);

	
	@ResponseBody
	@RequestMapping(value = "/ipaddr")
	public ResponseBean<Object> ipaddr(HttpServletRequest request){

		Map<String, Object> result = new HashMap<String, Object>();
	    String ip = null;

	    //X-Forwarded-For：Squid 服务代理
	    String ipAddresses = request.getHeader("X-Forwarded-For");

	    if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
	        //Proxy-Client-IP：apache 服务代理
	        ipAddresses = request.getHeader("Proxy-Client-IP");
	    }

	    if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
	        //WL-Proxy-Client-IP：weblogic 服务代理
	        ipAddresses = request.getHeader("WL-Proxy-Client-IP");
	    }

	    if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
	        //HTTP_CLIENT_IP：有些代理服务器
	        ipAddresses = request.getHeader("HTTP_CLIENT_IP");
	    }

	    if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
	        //X-Real-IP：nginx服务代理
	        ipAddresses = request.getHeader("X-Real-IP");
	    }

	    //有些网络通过多层代理，那么获取到的ip就会有多个，一般都是通过逗号（,）分割开来，并且第一个ip为客户端的真实IP
	    if (ipAddresses != null && ipAddresses.length() != 0) {
	        ip = ipAddresses.split(",")[0];
	    }

	    //还是不能获取到，最后再通过request.getRemoteAddr();获取
	    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
	        ip = request.getRemoteAddr();
	    }
		result.put("ipaddr", ip);
		Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String headerValue = request.getHeader(headerName);
            System.out.println(headerName + ": " + headerValue);
            result.put(headerName, headerValue);
        }

		return new ResponseBean<Object>(true, result);
	}
	
	@ResponseBody
	@RequestMapping(value = "/instance/search")
	public ResponseBean<Object> searchInstance(@RequestBody InstanceSearchBean mgtsInstanceSearchBean) {
		logger.info("search接口开始");
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Map<String, Object> returnMap = mgtsInstanceService.getInstances(mgtsInstanceSearchBean);
			result.put("resultList", returnMap.get("resultList"));
			result.put("facetList", returnMap.get("facetList"));
			result.put("pager", mgtsInstanceSearchBean.getPager());
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.info("search接口结束");
		return new ResponseBean<Object>(true, result);
	}

	// 地图检索1--地名
	@ResponseBody
	@RequestMapping(value = "/map")
	public ResponseBean<Object> placeInArea(InstanceSearchBean mgtsInstanceSearchBean,String points, @RequestBody(required = false) CommonSearchBean bean) throws ParseException {
		logger.info("search接口开始");
		
		List<Map<String, Object>> result =mgtsInstanceService.getPlacesInArea(mgtsInstanceSearchBean,points,bean);

		logger.info("search接口结束");
		return new ResponseBean<Object>(true, result);
	}

	// 地图检索1--地名
	@ResponseBody
	@RequestMapping(value = "/area")
	public ResponseBean<Object> area(String freetext, String points,String startYear, String endYear, @RequestBody(required = false) CommonSearchBean bean) throws ParseException {
		logger.info("search接口开始");
		
		List<Map<String, Object>> result = mgtsInstanceService.getPlacesInArea(freetext, points, startYear, endYear,bean);

		logger.info("search接口结束");
		return new ResponseBean<Object>(true, result);
	}
	
	// 地图检索1--Count
	@ResponseBody
	@RequestMapping(value = "/areaCount")
	public ResponseBean<Object> areaCount(String freetext, String points,String startYear, String endYear, @RequestBody(required = false) CommonSearchBean bean) {
		logger.info("search接口开始");
		
		List<Map<String, Object>> result = mgtsInstanceService.getPlacesInAreaCount(freetext, points, startYear, endYear);

		logger.info("search接口结束");
		return new ResponseBean<Object>(true, result);
	}
	
	//地图检索2--palce
	//https://red.library.sh.cn/gmwx/instance/search?placeUri=http://data.library.sh.cn/entity/place/mi3todp8f6toios5&freetext=
	@ResponseBody
	@RequestMapping(value = "/place")
	public  ResponseBean<Object> placeInAreaInsatnce(String placeUri,String freetext,Pager pager, String startYear, String endYear, @RequestBody(required = false) CommonSearchBean bean){
		logger.info("search接口开始");
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Map<String, Object> returnMap = mgtsInstanceService.getInstancesWithPlace(placeUri, freetext, startYear, endYear, pager,bean);
			result.put("resultList", returnMap.get("resultList"));
			result.put("pager", pager);
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.info("search接口结束");
		return new ResponseBean<Object>(true, result);

	}
	// 分类
	@ResponseBody
	@RequestMapping(value = "/class")
	public ResponseBean<Object> searchInstanceClass() {
		logger.info("search接口开始");
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Map<String, Object> returnMap = mgtsInstanceService.getClassification();
			result.put("classes", returnMap.get("classes"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.info("search接口结束");
		return new ResponseBean<Object>(true, result);
	}

	// workDetail
	@ResponseBody
	@RequestMapping("/work")
	public ResponseBean<Object> workDetail(@RequestBody InstanceSearchBean mgtsInstanceSearchBean) {
		logger.info("search接口开始");
		Map<String, Object> result = new HashMap<String, Object>();
		try {

			Map<String, Object> returnMap = mgtsInstanceService.getWorkDetail(mgtsInstanceSearchBean);
			result.put("resultList", returnMap.get("resultList"));
			result.put("facetList", returnMap.get("facetList"));
			result.put("pager", mgtsInstanceSearchBean.getPager());
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.info("search接口结束");
		return new ResponseBean<Object>(true, result);
	}

	// instanceDetail
	@ResponseBody
	@RequestMapping("/instance")
	public ResponseBean<Object> instanceDetail(@RequestBody HashMap<String, String> map) {
		logger.info("search接口开始");
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			result = mgtsInstanceService.getInstancesDetail(map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.info("search接口结束");
		return new ResponseBean<Object>(true, result);
	}

	// instanceDetail
	@ResponseBody
	@GetMapping("/instanceByUri/")
	public ResponseBean<Object> instanceDetail(String uri) {
		logger.info("search接口开始");
		HashMap<String, String> map = new HashMap<>();
		map.put("data", uri);
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			result = mgtsInstanceService.getInstancesDetail(map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.info("search接口结束");
		return new ResponseBean<Object>(true, result);
	}

	// instanceDetail
	@ResponseBody
	@RequestMapping("instance/multsearch")
	public ResponseBean<Object> multsearch(@RequestBody CommonSearchBean bean) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Map<String, Object> returnMap = mgtsInstanceService.multsearch(bean);
			result.putAll(returnMap);
			result.put("pager", bean.getPager());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ResponseBean<Object>(true, result);
	}

}
